package com.zhentao.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.common.constants.WemediaConstants;
import com.zhentao.mapper.WmMaterialMapper;
import com.zhentao.mapper.WmNewsMapper;
import com.zhentao.mapper.WmNewsMaterialMapper;
import com.zhentao.mapper.WmUserMapper;
import com.zhentao.model.common.dtos.PageResponseResult;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.wemwdia.dto.NewsAuthDto;
import com.zhentao.model.wemwdia.dto.WmNewsDownOrUpDto;
import com.zhentao.model.wemwdia.dto.WmNewsDto;
import com.zhentao.model.wemwdia.dto.WmNewsPageReqDto;
import com.zhentao.model.wemwdia.pojo.WmMaterial;
import com.zhentao.model.wemwdia.pojo.WmNews;
import com.zhentao.model.wemwdia.pojo.WmNewsMaterial;
import com.zhentao.model.wemwdia.pojo.WmUser;
import com.zhentao.service.WmNewsService;
import com.zhentao.service.WmNewsTaskService;
import com.zhentao.utils.common.WmUserThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class WmNewsServiceImpl implements WmNewsService {
    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    @Autowired
    private WmUserMapper wmUserMapper;
//    @Autowired
//    private WmNewsAutoScanServiceImpl autoScanService;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
//        参数校验
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        参数统一
        WmNews wmNews=new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
//        补齐属性
        wmNews.setUserId(WmUserThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable((short) 1);
//        提交时间 状态是 1是提交 0是保存草稿 1提交的时候才有时间
        if(dto.getStatus() == 1){
            wmNews.setSubmitedTime(new Date());
        }
//        获取文章封面 将图片集合改成字符串，用逗号隔开
        if(dto.getImages() != null && dto.getImages().size() > 0){
            String image = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(image);
        }
//        如果是封面 自动 则文件类型为-1 数据库中不能存负数 转换成4
        if(dto.getType() == WemediaConstants.WM_NEWS_TYPE_AUTO){
            dto.setType((short) 4);
            wmNews.setType((short) 4);
        }
//        增加数据库/修改根据id
//        判断是新增还是修改
        if(dto.getId() == null){
            wmNewsMapper.insert(wmNews);
        }else {
//        修改操作 -需要删除素材内容/和封面关系
//            删除关联关系
            Integer newId = dto.getId();
            LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(WmNewsMaterial::getNewsId,newId );
            wmNewsMaterialMapper.delete(lambdaQueryWrapper);
//            修改
            wmNewsMapper.updateById(wmNews);
        }
//        新增关联
//        处理封面  封面是自己上传的/封面是自动获取的
//        如果是4 获取到素材id的集合
        if(dto.getType() != 4){ //自己上传的
            List<String> images = dto.getImages();
            List<Integer> mids=new ArrayList<>();
            for (String image : images) {
                LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper=new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(WmMaterial::getUrl, image);
                WmMaterial wmMaterial = wmMaterialMapper.selectOne(lambdaQueryWrapper);
                mids.add(wmMaterial.getId());
            }
//            按照封面获取一张图片 type=1
            wmNewsMaterialMapper.saveRelations((short) 1,wmNews.getId(),mids);
        }else { //自动上传的
            List<Map> maps=JSON.parseArray(dto.getContent(),Map.class);
            List<String> images=new ArrayList<>();
            for (Map map : maps) {
//                传过来一个图片
                if(map.get("type").equals("image")){
                    String url = (String) map.get("value");
                    images.add(url);
                }
            }
//            下面图片的操作都是对已存在的数据操作
//            如果内容中没有图片
            if(images.size()==0){ //内容没有图片

                WmNews wmNews1=new WmNews();
                wmNews1.setId(wmNews1.getId());
                wmNews1.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }else {
                if(images.size()==1){
                    // size=1  type=1  size=2 type=1 size=3 type=3 size=4 type=3
                    WmNews wmNews1=new WmNews();
                    wmNews1.setId(wmNews1.getId());
                    wmNews1.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
//                    把图片集合转换成字符串以逗号分隔的形式存储
                    String image = StringUtils.join(images, ",");
                    wmNews1.setImages(image);
                    wmNewsMapper.updateById(wmNews1);

                    List<Integer> mids=new ArrayList<>();
                    for (Integer mid : mids) {
                        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper=new LambdaQueryWrapper<>();
                        lambdaQueryWrapper.eq(WmMaterial::getUrl, image);
                        WmMaterial wmMaterial = wmMaterialMapper.selectOne(lambdaQueryWrapper);
                        mids.add(wmMaterial.getId());
                    }
                    wmNewsMaterialMapper.saveRelations((short) 1, wmNews.getId(), mids);
                }
            }
        }
        if(dto.getStatus()==1){
//            autoScanService.autoScanWnMews(wmNews.getId());
            System.out.println("调用审核文章的服务--》进行修改");
            //将原有的直接调用自动审核的接口修改成添加到redis消息队列里面
            wmNewsTaskService.addNewsToTask(wmNews);
        }
        //处理内容与素材直接的关系  从里面里面吧素材获取到url -- id  添加操作
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.检查参数
        dto.checkParam();
        //2.分页查询
        Page<WmNews> page=new Page<>(dto.getPage(),dto.getSize());
        QueryWrapper<WmNews> queryWrapper=new QueryWrapper<>();
        //select xxx from xx where userid=1  if(channelId!=null){and   channelId=null }
        //1.userId
        queryWrapper.lambda().eq(WmNews::getUserId, WmUserThreadLocalUtil.getUser().getId());
//      频道
        queryWrapper.lambda().eq(dto.getChannelId() != null,WmNews::getChannelId,dto.getChannelId());
//      状态
        queryWrapper.lambda().eq(dto.getStatus() != null,WmNews::getStatus,dto.getStatus());
//       关键字
        queryWrapper.lambda().eq(dto.getKeyword() !=null,WmNews::getLabels,dto.getKeyword());
//      时间
        if(dto.getBeginPubDate() != null && dto.getEndPubDate() != null){
            queryWrapper.lambda().between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        page=wmNewsMapper.selectPage(page, queryWrapper);
        PageResponseResult responseResult=new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setCode(200);
        responseResult.setErrorMessage("请求成功");
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    @Override
    public ResponseResult downOrUp(WmNewsDownOrUpDto dto) {
        //1.检查参数
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = wmNewsMapper.selectById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //3.判断文章是否已发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章不是发布状态不能上下架");
        }
        //4.修改文章enable
        wmNews.setEnable(dto.getEnable());
        wmNewsMapper.updateById(wmNews);
        if(wmNews.getArticleId()!=null){
            Map<String,Object> map = new HashMap<>();
            map.put("articleId",wmNews.getArticleId());
            map.put("enable",dto.getEnable());
            //发送消息到kafka
            kafkaTemplate.send("articleDownOrUpTopic",JSON.toJSONString(map));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult list_vo(NewsAuthDto dto) {
        dto.checkParam();
        Page<WmNews> page=new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmNews> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(dto.getStatus() != null, WmNews::getStatus,dto.getStatus());
        wrapper.like(StringUtils.isNotBlank(dto.getTitle()), WmNews::getTitle,dto.getTitle());
        page=wmNewsMapper.selectPage(page,wrapper);
        for (WmNews wmNews : page.getRecords()) {
            WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
            wmNews.setAuthorName(wmUser.getName());
        }
        PageResponseResult result=new PageResponseResult();
        result.setTotal((int) page.getTotal());
        result.setSize((int) page.getSize());
        result.setData(page.getRecords());
        result.setCode(200);
        result.setCurrentPage((int) page.getCurrent());
        return result;
    }

    @Override
    public ResponseResult one_vo(Integer id) {
        WmNews wmNews = wmNewsMapper.selectById(id);
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        wmNews.setAuthorName(wmUser.getName());
        return ResponseResult.okResult(wmNews);
    }

    @Override
    public ResponseResult auth_fail(NewsAuthDto dto) {
        WmNews wmNews=new WmNews();
        wmNews.setStatus(dto.getStatus().shortValue());
        wmNews.setReason(dto.getMsg());
        wmNews.setId(dto.getId());
        wmNewsMapper.updateById(wmNews);
        return ResponseResult.okResult(200,"ok");
    }

    @Override
    public ResponseResult auth_pass(NewsAuthDto dto) {
        WmNews wmNews=new WmNews();
        wmNews.setStatus(dto.getStatus().shortValue());
        wmNews.setId(dto.getId());
        wmNewsMapper.updateById(wmNews);
        return ResponseResult.okResult(200,"ok");
    }
}
